<template>
  <MainSlot v-loading="loading">
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" :unfoldFlag="unfoldFlag" @search="search"
        @isUnfold="(v) => { unfoldFlag = v }">
      </SearchForm>
    </template>
    <template v-slot:table>
      <div class="drugsList" ref="drugsList">
        <div class="drugInfo" v-for="item, index in facilityOutPutList" :key="index">
          <div class="point"></div>
          <div>养殖设施：<span class="info">{{ item.facilityName || '鱼塘设施' }}</span></div>
          <div>养殖面积：<span class="info">{{ item.scope || '-' }}</span>亩</div>
          <div>总产量：<span class="info">{{ item.totalNum || '-' }}</span>斤</div>
          <div>亩均产量：<span class="info">{{ item.averageNum || '-' }}</span>斤</div>
        </div>
        <span class="facilityOutPutList" v-show="facilityOutPutList.length == 0">暂无产出数据!</span>
      </div>
      <div class="echarts" ref="echarts" v-show="facilityOutPutList.length > 0">
        <!-- <LineCharts></LineCharts> -->
        <HorizontalBarChart v-if="retsetEcharts" :options="chartOptions"></HorizontalBarChart>
      </div>
    </template>
  </MainSlot>
</template>
<script>
import MainSlot from "@/components/MainSlot";
import HorizontalBarChart from "./components/horizontalBarChart.vue";
import LineCharts from "./components/lineCharts.vue";
import SearchForm from '@/components/SearchForm';
import outputManagment from '@/api/outputManagment/outputQuery.js';
import facilityManagement from '@/api/digtalOperation/facilityManagement.js';
import { formatTime } from '@/utils/fmtTime.js';

export default {
  components: { MainSlot, LineCharts, SearchForm, HorizontalBarChart },
  data() {
    return {
      retsetEcharts: false,
      unfoldFlag: false,
      loading: false,
      facilityList: [],
      facilityOutPutList: [],
      searchFormData: {},
      chartOptions: {
        tooltip: {
          trigger: 'axis',
          formatter: function (params) {
            let text = [params[0].name];
            let desc = '斤';
            if (params[0]) {
              var data = params[0].data || '--';
              var seriesName = params[0].seriesName || '--';
              text.push(seriesName + ': ' + data + desc)
            }
            if (params[1]) {
              var data_1 = params[1].data || '--';
              var seriesName_1 = params[1].seriesName || '--';
              text.push(seriesName_1 + ': ' + data_1 + desc)
            }
            return text.join('</br>');
          }
        },
        grid: {
          top: 100,
          left: 120,
          right: 50
        },
        legend: {
          data: ['亩产', '总产']
        },
        xAxis: {
          type: 'value'
        },
        yAxis: {
          type: 'category',
          data: []
        },
        series: [{
          data: [],
          type: 'bar',
          name: '亩产'
        },
        {
          data: [],
          type: 'bar',
          name: '总产'
        }]
      },
      isYear: false,
      formItemList: [{
        label: '养殖设施',
        type: 'select',
        selectOptions: [],
        param: 'facilityIdList',
        defaultSelect: '',
        multiple: true,
        collapseTags: true,
        isShow: true
      }, {
        label: '养殖日期',
        type: 'datetimerange',
        param: 'dataList',
        isShow: true
      }, {
        label: '按年/日期查',
        type: 'select',
        selectOptions: [{ value: 'isYear', text: '按年查' }, { value: 'noYear', text: '按月查' }],
        param: 'isYear',
        defaultSelect: 'noYear',
        isShow: true
      }, {
        label: '年份',
        type: 'year',
        param: 'queryYear',
        isShow: true
      }
      ]
    }
  },
  mounted() {
    this.initData();
  },
  methods: {
    async initData() {
      //获取养殖设施；
      let { data: facilityList } = await facilityManagement.getFacilityListByConditionAll({
        breedType: sessionStorage.breedType
      });
      this.facilityList = facilityList || [];
      this.facilityIdList = this.facilityList.map(item => { return item.facilityId });

      this.queryByFacility();
      this.setFormOptions();
    },
    setFormOptions() {
      let list = JSON.parse(JSON.stringify(this.formItemList));
      this.formItemList = []
      list.forEach((item, index) => {
        if (item.param.indexOf('facilityIdList') !== -1) {
          console.log(this.facilityList)
          let selectOptions = this.facilityList.map(data => {
            return {
              text: data.facilityName, value: data.facilityId
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
      });
      this.$nextTick(() => {
        this.$set(this, 'formItemList', list)
        console.log(this.formItemList)
      })
    },
    search(data) {
      console.log(data.queryYear, data.facilityIdList)
      if (!data.isYear && data.dataTimeList && data.queryYear) {
        this.$message.warning('请选择按年/按日期查询')
        return
      } else {
        if (data.isYear == 'noYear' || !data.isYear) {
          this.isYear = false;
        } else {
          this.isYear = true;
        }
      }
      let dataList = data.dataList && data.dataList.length ? data.dataList || [] : []
      this.searchFormData = {
        facilityIdList: data.facilityIdList || [],
        startDate: dataList[0] || null,
        endDate: dataList[1] || null,
        queryYear: data.queryYear ? new Date(data.queryYear).getFullYear() : null
      }
      this.queryByFacility()
    },
    queryByFacility() {
      let params = [];
      //获取单位不是亩或者平方米的设施
      let noqueryList = this.facilityList.filter(item => {
        return !item.unitName || !(item.unitName == '亩' || item.unitName == '平方米') || !item.scope
      })
      //获取单位是亩或者平方米的设施
      let queryList = this.facilityList.filter(item => {
        console.log(item.facilityName, item.unitName && item.scope && (item.unitName == '亩' || item.unitName == '平方米'))
        return item.unitName && item.scope && (item.unitName == '亩' || item.unitName == '平方米')
      })
      //单位不是亩或者平方米的设施做出提示
      if (noqueryList.length > 0) {
        let textList = queryList.map(item => {
          return item.facilityName
        })
        this.$message.warning(textList.join(';') + ';未配置面积或单位配置非面积单位，请重新配置单位为亩或者平方米!')
      }
      //重置表格数据
      this.$set(this.chartOptions.yAxis, 'data', []);
      this.$set(this.chartOptions, 'series', [{
        data: [],
        type: 'bar',
        name: '总产',
        barWidth: 20
      }, {
        data: [],
        type: 'bar',
        name: '亩产',
        barWidth: 20
      }]);
      //符合条件的设施获取设施的基本数据请求产量分析
      queryList.forEach(item => {
        let newDate = new Date();
        let year = new Date().getFullYear();
        let startDate = '';
        let endDate = '';
        let facilityIdList = this.searchFormData.facilityIdList || [];
        let unitName = item.unitName;
        let scope = item.scope;
        if (this.isYear) {
          let y = this.searchFormData.queryYear || year
          startDate = `${y}-01-01`;
          endDate = `${y}-12-31`;
        } else if (!this.isYear) {
          startDate = this.searchFormData.startDate || formatTime(newDate.setDate(newDate.getDate() - 15), 'yyyy-MM-dd');
          endDate = this.searchFormData.endDate || formatTime(newDate.setDate(newDate.getDate() + 16), 'yyyy-MM-dd');
        }
        this.chartOptions.yAxis.data.push(item.facilityName);
        this.chartOptions.series[0].data.push(0);
        if (facilityIdList.length == 0 || (facilityIdList.length > 0 && facilityIdList.includes(item.facilityId))) {
          params.push({
            facilityId: item.facilityId,
            facilityName: item.facilityName,
            scope: scope,
            unitName: unitName,
            startDate: startDate,
            endDate: endDate,
          })
        }
      })
      //重置图标
      this.retsetEcharts = false;
      this.facilityOutPutList = [];
      console.log(params, '--------------------')
      if (params.length > 0) {
        outputManagment.queryByFacility(params).then(res => {
          this.retsetEcharts = true;
          if (res.code) {
            this.chartOptions.yAxis.data = []
            this.chartOptions.series[0].data = [];
            this.chartOptions.series[1].data = [];
            if (res.data.length) {
              this.facilityOutPutList = res.data;
              res.data.forEach((item, index) => {
                item.facilityName = item.facilityName || queryList[index].facilityName
                this.chartOptions.yAxis.data.push(item.facilityName);
                this.chartOptions.series[0].data.push(item.totalNum || 0);
                this.chartOptions.series[1].data.push(item.averageNum || 0);
              })
            } else {
              this.facilityOutPutList = []
            }
          } else {
            this.$message.warning(res.msg || '查询产量失败')
          }
        }).catch(err => {
          console.log(err);
          this.$message.warning(err)
        })
      }
    },
  }
};
</script>
<style lang="scss" scoped>
.table {
  height: 100%;
}

.drugsList {
  width: 100%;
  max-height: 200px;
  min-height: 100px;
  padding: 0 20px;
  overflow-y: auto;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-wrap: wrap;
  transition: all 0.2s;

  .drugInfo {
    width: 50%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    font-size: 14px;
    line-height: 36px;

    .point {
      width: 10px;
      height: 10px;
      background: #02a0fc;
    }

    &>div {
      margin-right: 20px;

      .info {
        color: #999999;
      }
    }
  }

}

.drugsList:hover {
  background: #f1f1f1;
}

.echarts {
  padding: 20px;
}

.facilityOutPutList {
  display: block;
  width: 100%;
  text-align: center;
  color: #02a0fc;
}
</style>